﻿using MQTTnet;
using MQTTnet.Client;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
using Manager.Service;
using MySqlX.XDevAPI;

namespace Manager.Background
{
    public class MqttBackService : IHostedService, IDisposable
    {
        private readonly IMqttClient _client;
        private MqttClientOptions options;
        private Timer reconnectTimer;

        public MqttBackService(IMqttClient client)
        {
            _client = client;
            InitializeMqttOptions();
        }

        private void InitializeMqttOptions()
        {
            options = new MqttClientOptionsBuilder()
                .WithClientId("MQTTClient")
                .WithTcpServer("139.196.170.188", 1883) 
                .WithCredentials("sammy", "123456") 
                .Build();
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await ConnectAsync();
            reconnectTimer = new Timer(async _ => await ReconnectAsync(), null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            reconnectTimer?.Change(Timeout.Infinite, 0);
            return _client.DisconnectAsync();
        }

        public async Task ConnectAsync()
        {
            try
            {
                if (!_client.IsConnected)
                {
                    //await _client.ConnectAsync(options);
                    Console.WriteLine("MQTT连接成功");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"MQTT连接失败：{ex.Message}");
            }
        }

        private async Task ReconnectAsync()
        {
            if (!_client.IsConnected)
            {
                await ConnectAsync();
            }
        }

        public void Dispose()
        {
            reconnectTimer?.Dispose();
            _client?.Dispose();
        }
    }
}
